package com.yff.tuan.interceptor;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Aspect
public class OperationLog {
	private Logger logger =  LoggerFactory.getLogger(OperationLog.class);
	
	@Pointcut("execution(* com.yff.tuan.controller.*.*(..))")  
    public void bizPointCut() {  
        // 定义�?个pointcut，下面用Annotation标注的�?�知方法可以公用这个pointcut  
    }  
	
    @Before("bizPointCut()")  
    public void myBeforeAdvice(JoinPoint jionpoint) {// 如果�?要知道拦截的方法的信息，也可以需添加JoinPoint参数  
        Object[] os = jionpoint.getArgs();
        
        String targetMethodName = jionpoint.getSignature().getName(); 
        
    	String type2  = jionpoint.getTarget().getClass().getName(); 
        String logInfoText2 =  type2;  
        long threadId = Thread.currentThread().getId();
        
        StringBuffer sb = new StringBuffer();
        for(int i = 0;i<os.length;i++)
        {
        	Object obj = os[i];
        	if (null != obj) {
            	String str = obj.toString();
            	sb.append(" "+str +":");
        	}
        }

        logger.info("Thread["+threadId+"]--Before--"+logInfoText2+"--"+targetMethodName+sb.toString());            
    }
	
    @AfterReturning(pointcut="bizPointCut()",returning="returnValue")
    public void afterReturning(JoinPoint jionpoint,Object returnValue){
        long threadId = Thread.currentThread().getId();
        String targetMethodName = jionpoint.getSignature().getName(); 
        
        String response ="";
        try{
        	JSONObject jsonObj = JSONObject.fromObject(returnValue);
        	response = jsonObj.toString();
        }catch(Exception e){
        	try{
        		JSONArray jsonArray = JSONArray.fromObject(returnValue);
        		response = jsonArray.toString();
        	}catch(Exception e1){
        		logger.info("API response is "+returnValue);
        	}
        }
    	logger.info("Thread["+threadId+"]--Response--:--of "+targetMethodName+ " is :"+ response);
    }
	
}
